<template>
  <j-modal title="打印领料单" :width="800" :visible="visible" :footer="null" @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <div id="printArea" class="print-content">
        <div class="print-header">
          <h1>领料单</h1>
          <div class="print-info">
            <div class="print-info-item">
              <span class="label">领料单号：</span>
              <span class="value">{{ model.requisitionNo }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">领料日期：</span>
              <span class="value">{{ model.requisitionDate }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">优化软件类型：</span>
              <span class="value">{{ model.optimizationSoftwareType == '0' ? '长风' : '新格尔' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">备注：</span>
              <span class="value">{{ model.remark || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 型材明细 -->
        <div v-if="showProfileTable" class="print-table-container">
          <h2>型材明细</h2>
          <table class="print-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>型材编号</th>
                <th>型材名称</th>
                <th>颜色</th>
                <th>长度(mm)</th>
                <th v-if="model.optimizationSoftwareType == '0'">宽度(mm)</th>
                <th v-if="model.optimizationSoftwareType == '0'">高度(mm)</th>
                <th>数量(根)</th>
                <th>重量(kg)</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in profileDataSource" :key="item.id">
                <td>{{ index + 1 }}</td>
                <td>{{ item.profileCode }}</td>
                <td>{{ item.profileName }}</td>
                <td>{{ item.color }}</td>
                <td>{{ item.length }}</td>
                <td v-if="model.optimizationSoftwareType == '0'">{{ item.width }}</td>
                <td v-if="model.optimizationSoftwareType == '0'">{{ item.height }}</td>
                <td>{{ item.quantity }}</td>
                <td>{{ item.weight }}</td>
                <td>{{ item.remark || '-' }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 配件明细 -->
        <div v-if="showAccessoryTable" class="print-table-container">
          <h2>配件明细</h2>
          <table class="print-table">
            <thead>
              <tr>
                <th>序号</th>
                <th v-if="model.optimizationSoftwareType == '0'">窗号</th>
                <th>配件编号</th>
                <th>配件名称</th>
                <th v-if="model.optimizationSoftwareType == '0'">规格</th>
                <th v-if="model.optimizationSoftwareType == '0'">数量</th>
                <th v-if="model.optimizationSoftwareType == '1'">长度/数量</th>
                <th>单位</th>
                <th v-if="model.optimizationSoftwareType == '0'">品牌</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in accessoryDataSource" :key="item.id">
                <td>{{ index + 1 }}</td>
                <td v-if="model.optimizationSoftwareType == '0'">{{ item.windowNo }}</td>
                <td>{{ item.accessoryCode }}</td>
                <td>{{ item.accessoryName }}</td>
                <td v-if="model.optimizationSoftwareType == '0'">{{ item.specification }}</td>
                <td v-if="model.optimizationSoftwareType == '0'">{{ item.quantity }}</td>
                <td v-if="model.optimizationSoftwareType == '1'">{{ item.lengthQuantity }}</td>
                <td>{{ item.unit }}</td>
                <td v-if="model.optimizationSoftwareType == '0'">{{ item.brand }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="print-footer">
          <div class="print-signature">
            <div class="signature-item">
              <span>仓库管理员：</span>
              <span class="signature-line"></span>
            </div>
            <div class="signature-item">
              <span>领料人：</span>
              <span class="signature-line"></span>
            </div>
            <div class="signature-item">
              <span>领料日期：</span>
              <span class="signature-line"></span>
            </div>
          </div>
        </div>
      </div>

      <div class="print-actions">
        <a-button type="primary" icon="printer" @click="handlePrint">打印</a-button>
        <a-button style="margin-left: 8px" icon="download" @click="handleExport">导出PDF</a-button>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction } from '@/api/manage'
// 使用import方式导入jspdf
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

export default {
  name: 'RequisitionPrintModal',
  data() {
    return {
      visible: false,
      model: {},
      confirmLoading: false,

      // 型材明细相关
      profileDataSource: [],
      showProfileTable: true,

      // 配件明细相关
      accessoryDataSource: [],
      showAccessoryTable: true,

      url: {
        getRequisition: '/wms/requisition/queryById',
        getProfileList: '/wms/requisition/getProfileList',
        getAccessoryList: '/wms/requisition/getAccessoryList',
      },
    }
  },
  methods: {
    show(id) {
      this.visible = true
      this.loadData(id)
    },

    loadData(id) {
      this.confirmLoading = true

      // 清空数据
      this.model = {}
      this.profileDataSource = []
      this.accessoryDataSource = []

      // 加载领料单数据
      getAction(`${this.url.getRequisition}?id=${id}`)
        .then((res) => {
          if (res.success) {
            this.model = res.result || {}

            // 根据优化软件类型调整表格显示
            this.showProfileTable = true
            this.showAccessoryTable = true

            // 加载型材明细
            this.loadProfileData(id)

            // 加载配件明细
            this.loadAccessoryData(id)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 加载型材明细数据
    loadProfileData(requisitionId) {
      getAction(`${this.url.getProfileList}/${requisitionId}`).then((res) => {
        if (res.success) {
          this.profileDataSource = res.result || []
        }
      })
    },

    // 加载配件明细数据
    loadAccessoryData(requisitionId) {
      getAction(`${this.url.getAccessoryList}/${requisitionId}`).then((res) => {
        if (res.success) {
          this.accessoryDataSource = res.result || []
        }
      })
    },

    // 打印
    handlePrint() {
      // 创建新窗口进行打印，避免影响当前页面
      const printWindow = window.open('', '_blank', 'width=800,height=600')
      const printContent = document.getElementById('printArea').innerHTML

      printWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
            <title>领料单打印</title>
            <style>
              body { margin: 0; padding: 20px; font-family: Arial, sans-serif; }
              .print-content { padding: 0; background-color: #fff; }
              .print-header { text-align: center; margin-bottom: 20px; }
              .print-header h1 { font-size: 24px; font-weight: bold; margin-bottom: 20px; }
              .print-info { display: flex; flex-wrap: wrap; text-align: left; }
              .print-info-item { width: 50%; margin-bottom: 10px; }
              .print-info-item .label { font-weight: bold; }
              .print-table-container { margin-bottom: 20px; }
              .print-table-container h2 { font-size: 18px; font-weight: bold; margin-bottom: 10px; }
              .print-table { width: 100%; border-collapse: collapse; border: 1px solid #000; }
              .print-table th, .print-table td { border: 1px solid #000; padding: 5px; text-align: center; }
              .print-table th { background-color: #f0f0f0; }
              .print-footer { margin-top: 30px; }
              .print-signature { display: flex; justify-content: space-between; }
              .signature-item { margin-bottom: 10px; }
              .signature-line { display: inline-block; min-width: 150px; border-bottom: 1px solid #000; text-align: center; }
              @media print {
                @page { margin: 0.5in; }
                body { margin: 0; }
              }
            </style>
          </head>
          <body>
            ${printContent}
          </body>
          </html>
        `)

      printWindow.document.close()

      // 等待内容加载完成后打印
      printWindow.onload = function () {
        printWindow.print()
        printWindow.close()
      }
    },

    // 导出PDF
    handleExport() {
      this.confirmLoading = true

      const element = document.getElementById('printArea')

      html2canvas(element, {
        scale: 2,
        useCORS: true,
        logging: false,
      })
        .then((canvas) => {
          const imgData = canvas.toDataURL('image/png')
          // jsPDF 3.0.1版本的正确实例化方式
          const pdf = new jsPDF({
            orientation: 'portrait',
            unit: 'mm',
            format: 'a4',
          })
          const imgWidth = 210
          const pageHeight = 297
          const imgHeight = (canvas.height * imgWidth) / canvas.width
          let heightLeft = imgHeight
          let position = 0

          pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
          heightLeft -= pageHeight

          while (heightLeft > 0) {
            position = heightLeft - imgHeight
            pdf.addPage()
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
            heightLeft -= pageHeight
          }

          pdf.save(`领料单-${this.model.requisitionNo}.pdf`)
          this.confirmLoading = false
        })
        .catch((error) => {
          console.error('导出PDF失败', error)
          this.$message.error('导出PDF失败')
          this.confirmLoading = false
        })
    },

    handleCancel() {
      this.visible = false
    },
  },
}
</script>

<style scoped>
.print-content {
  padding: 20px;
  background-color: #fff;
}

.print-header {
  text-align: center;
  margin-bottom: 20px;
}

.print-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.print-info {
  display: flex;
  flex-wrap: wrap;
  text-align: left;
}

.print-info-item {
  width: 50%;
  margin-bottom: 10px;
}

.print-info-item .label {
  font-weight: bold;
}

.print-table-container {
  margin-bottom: 20px;
}

.print-table-container h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.print-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #000;
}

.print-table th,
.print-table td {
  border: 1px solid #000;
  padding: 5px;
  text-align: center;
}

.print-table th {
  background-color: #f0f0f0;
}

.print-footer {
  margin-top: 30px;
}

.print-signature {
  display: flex;
  justify-content: space-between;
}

.signature-item {
  margin-bottom: 10px;
}

.signature-line {
  display: inline-block;
  min-width: 150px;
  border-bottom: 1px solid #000;
  text-align: center;
}

.print-actions {
  margin-top: 20px;
  text-align: center;
}

@media print {
  .print-actions {
    display: none;
  }
}
</style> 